package com.example.yiqiuser.util;

import com.example.yiqiuser.entity.OperLog;
import com.example.yiqiuser.entity.Tuser;
import com.example.yiqiuser.entity.User;
import com.example.yiqiuser.service.OperLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @create by: 周文达 (3220083246@qq.com)
 * @description: 日志记录工具类
 * @create time: 2023/4/12 21:02
 * @return
 */
@Component  //该注解表示，把该类交给spring管理
@Aspect //表示当前类为通知类
public class LogRecordUtil {

    //依赖操作日志的Service
    @Resource
    private OperLogService operLogService;

    @Resource
    private HttpSession session;

    @Resource
    private HttpServletRequest request;


    /**
     * 切入点配置
     *          编写切入点表达式
     */
    @Pointcut(value = "execution(* com.example.yiqiuser.service.impl.*.add*(..))" +
            "||execution(* com.example.yiqiuser.service.impl.*.update*(..))" +
            "||execution(* com.example.yiqiuser.service.impl.*.delete*(..))"
          )
    public void pointCut(){
    }


    /**
     * 后置通知：操作日志记录方法
     */
    @AfterReturning(pointcut = "pointCut()")
    public void recordLog(JoinPoint joinpoint){
        //实例化操作日志对象
        OperLog operLog=new OperLog();
        //获取执行方法名称
        String name = joinpoint.getSignature().getName();
        operLog.setTitle("后台管理"); //模块标题
        if(name.contains("add")){ //业务类型（0其它 1新增 2修改 3删除）
            operLog.setBusinessType(1);
        }else if(name.contains("update")){
            operLog.setBusinessType(2);
        }
        else if(name.contains("delete")){
            operLog.setBusinessType(3);
        }else {
            operLog.setBusinessType(0);
        }
        operLog.setMethod(name); //方法名称
        operLog.setOperatorType(1); //操作类别（0其它 1后台用户 2手机端用户）
        //获取登录人的session
        User userInfo = (User)session.getAttribute("userInfoA");

       // Object userInfoA = session.getAttribute("userInfoA");
       /* if(userInfo instanceof Tuser){
            Tuser tuser=(Tuser)userInfo;
            operLog.setOperName(tuser.getMobile());//操作人员账号
        }if(userInfoA instanceof User) {
            User user=(User)userInfoA;
            operLog.setOperName(user.getLoginName());//操作人员
        }*/
        System.out.println("================"+userInfo);
        operLog.setOperName(userInfo.getLoginName());//操作人员账号
        System.out.println("========================="+userInfo);
        operLog.setDeptName("暂无");//部门名称
        //获取URl
        String requestURI = request.getRequestURI();
        operLog.setOperUrl(requestURI);//请求URL
        //获取id地址
        String remoteAddr = request.getRemoteAddr();
        operLog.setOperIp(remoteAddr);//主机ip地址
        operLog.setOperLocation("暂无");//操作地点
        //获取执行方法的参数
        Object[] args = joinpoint.getArgs();
        String str=null;
        if(args!=null){
            str=args[0].getClass().getName();
        }
        operLog.setOperParam(str);//请求参数
        operLog.setStatus(0);//操作状态（0正常 1异常）
        operLog.setErrorMsg("暂无");
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = simpleDateFormat.format(new Date());
        operLog.setOperTime(format1);//操作时间
        //执行日志添加操作
        operLogService.insert(operLog);
        System.out.println("::============"+operLog);

    }

    /**
     * 异常通知：操作日志记录方法
     * @param joinPoint
     * @param e
     */
   // @AfterThrowing(pointcut = "pointCut()",throwing = "e")
    public void exceptionExecute(JoinPoint joinPoint,Exception e){
        //获取执行方法名称
        String name = joinPoint.getSignature().getName();
        //实例化操作日志对象
        OperLog operLog=new OperLog();
        operLog.setTitle("后台管理"); //模块标题
        if(name.contains("add")){ //业务类型（0其它 1新增 2修改 3删除）
            operLog.setBusinessType(1);
        }else if(name.contains("delete")){
            operLog.setBusinessType(2);
        }
        else if(name.contains("delete")){
            operLog.setBusinessType(3);
        }else {
            operLog.setBusinessType(0);
        }
        operLog.setMethod("name"); //方法名称
        operLog.setOperatorType(1); //操作类别（0其它 1后台用户 2手机端用户）
        //获取登录人的session
        //获取登录人的session
        Object userInfo = session.getAttribute("userInfo");
        Object userInfoA = session.getAttribute("userInfoA");
        if(userInfo instanceof Tuser){
            Tuser tuser=(Tuser)userInfo;
            operLog.setOperName(tuser.getMobile());//操作人员
        }
        if(userInfoA instanceof User) {
            User user=(User)userInfoA;
            operLog.setOperName(user.getLoginName());//操作人员
        }
        operLog.setDeptName("暂无");//部门名称
        //获取URl
        String requestURI = request.getRequestURI();
        operLog.setOperUrl(requestURI);//请求URL
        //获取id地址
        String remoteAddr = request.getRemoteAddr();
        operLog.setOperIp(remoteAddr);//主机ip地址
        operLog.setOperLocation("暂无");//操作地点
        //获取执行方法的参数
        Object[] args = joinPoint.getArgs();
        String str=null;
        if(args!=null){
            str=args[0].getClass().getName();
        }
        operLog.setOperParam(str);//请求参数
        operLog.setStatus(1);//操作状态（0正常 1异常）
        operLog.setErrorMsg(e.getMessage()); //异常信息
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = simpleDateFormat.format(new Date());
        operLog.setOperTime(format1);//操作时间
        //执行日志添加操作
        operLogService.insert(operLog);
    }
}
